package com.liuxvru.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuxvru.common.core.domain.entity.SysUser;
import com.liuxvru.common.utils.SecurityUtils;
import com.liuxvru.project.domain.ProjectUserAssignment;
import com.liuxvru.project.mapper.ProjectUserAssignmentMapper;
import com.liuxvru.project.service.IProjectUserAssignmentService;
import com.liuxvru.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;

/**
 * 项目与人员分配Service业务层处理
 *
 * @author liuxvru
 * @date 2024-11-22
 */
@Service
public class ProjectUserAssignmentServiceImpl extends ServiceImpl<ProjectUserAssignmentMapper, ProjectUserAssignment> implements IProjectUserAssignmentService {

    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 查询项目与人员分配列表
     *
     * @param projectUserAssignment 项目与人员分配
     * @return 项目与人员分配
     */
    @Override
    public List<ProjectUserAssignment> selectProjectUserAssignmentList(ProjectUserAssignment projectUserAssignment) {
        return baseMapper.selectProjectUserAssignmentList(projectUserAssignment);
    }

    @Override
    public List<ProjectUserAssignment> listByProjectId(Long projectId) {
        return baseMapper.selectList(new LambdaQueryWrapper<ProjectUserAssignment>().eq(ProjectUserAssignment::getProjectId, projectId));
    }

    @Override
    @Transactional
    public int addUser(ProjectUserAssignment user) {
        List<ProjectUserAssignment> projectUserAssignments = baseMapper.selectList(new LambdaQueryWrapper<ProjectUserAssignment>()
                        .eq(ProjectUserAssignment::getProjectId, user.getProjectId())
                        .eq(ProjectUserAssignment::getUserId, user.getUserId()));
        if(!projectUserAssignments.isEmpty()){
            throw new RuntimeException("该用户已分配,不可重复添加");
        }
        Long userId = SecurityUtils.getUserId();
        user.setCreatedBy(userId);
        user.setUpdatedBy(userId);
        return baseMapper.insert(user);
    }

    @Override
    public int upUser(ProjectUserAssignment user) {
        ProjectUserAssignment projectUserAssignment = new ProjectUserAssignment();
        projectUserAssignment.setAssignmentId(user.getAssignmentId());
        projectUserAssignment.setProjectRole(user.getProjectRole());
        projectUserAssignment.setUpdatedBy(SecurityUtils.getUserId());
        baseMapper.updateById(user);
        return 0;
    }

    @Override
    public int delUser(Long id) {
        return baseMapper.deleteById(id);
    }
}
